package com.lt.lumentracks.service.common;

import com.aliyuncs.exceptions.ClientException;
import com.lt.lumentracks.constant.FileConstant;
import com.lt.lumentracks.context.BaseContext;
import com.lt.lumentracks.entity.po.TempFile;
import com.lt.lumentracks.entity.vo.common.Result;
import com.lt.lumentracks.exception.BaseException;
import com.lt.lumentracks.service.ITempFileService;
import com.lt.lumentracks.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

@Slf4j
@Service
public class FileUploadService {

    @Autowired
    private AliOSSUtils aliOSSUtils;
    @Autowired
    private ITempFileService tempFileService;


    /**
     * 单文件上传（帖子相关）
     * @param file 上传的文件
     */
    @Transactional
    public Result<String> uploadFiles_post(MultipartFile file)  {
        try {
            Integer userId = BaseContext.getCurrentId(); // 从当前线程中，获取当前操作的用户的id

            // 1.先上传文件到阿里云oss
            String filePath = aliOSSUtils.upload(file, FileConstant.OSS_DIRECTORY_NAME_POST_PIC); //文件的请求路径

            // 2.将文件路径保存到【临时文件表】中
            TempFile tf = new TempFile();
            tf.setFileUrl(filePath);
            tf.setUserId(userId);
            tf.setCreateTime(LocalDateTime.now());
            tempFileService.save(tf);

            return Result.success(filePath);
        } catch (ClientException | IOException e) {
            log.error("文件上传失败：", e);
            throw new BaseException("文件上传失败");
        }
    }

}
